//
//  JPEmotionCollectionCell.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/6.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

class JPEmotionCollectionCell: UICollectionViewCell {
    
    //  按钮模型数组
    var emotions: [JPEmotion]? {
        didSet {
            guard let emotionArr = emotions else {
                return
            }
            
            for button in buttonArrM {
                button.isHidden = true
            }
            
            for (i,emotion) in emotionArr.enumerated() {
                
                buttonArrM[i].emotion = emotion
            }
            
        }
    }
    
    
    //  保存按钮的数组
    lazy var buttonArrM: [JPEmotionButton] = [JPEmotionButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        addEmotionButton()
    }
    
    private func addEmotionButton() {
        for _ in 0..<20 {
            let button = JPEmotionButton()
            button.titleLabel?.font = UIFont.systemFont(ofSize: 33)
            button.addTarget(self, action: #selector(emotionButtonAction(btn:)), for: .touchUpInside)
            
            self.contentView.addSubview(button)
            buttonArrM.append(button)
        }
        
    }
    
    @objc private func emotionButtonAction(btn: JPEmotionButton) {
        
        NotificationCenter.default.post(name: NSNotification.Name(DidSelectedEmotionNotification), object: btn.emotion)
        
        JPEmotionTool.sharedEmotionTool.saveRecentEmotion(emotion: btn.emotion!)
        (self.superview as! UICollectionView).reloadData()
        
        let window = UIApplication.shared.windows.last!
        
        let pointToWindow = self.convert(btn.center, to: window)
        
        let emtionPopView = JPEmotionPopView.emotionPopView()
        emtionPopView.center = CGPoint(x: pointToWindow.x, y: pointToWindow.y - emtionPopView.height / 2 + btn.height / 2)
        
        window.addSubview(emtionPopView)
        btn.isHidden = true
        emtionPopView.emotionButton.emotion = btn.emotion
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            btn.isHidden = false
            emtionPopView.removeFromSuperview()
        }
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let buttonWidth = width / 7
        let buttonHeight = height / 3
        
        for (i,button) in buttonArrM.enumerated() {
            let col = i % 7
            let row = i / 7
            
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            button.x = buttonWidth * CGFloat(col)
            button.y = buttonHeight * CGFloat(row)
        }
        
        
    }
}
